package io.agora.chatroom;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import org.allrtc.wrap.QttRtcEngine;

import java.util.ArrayList;
import java.util.List;

import io.agora.adapter.PopuwindowAdapter;
import io.agora.adapter.UsesAdapter;
import io.agora.linstener.MyOnSeekBarChangeListener;
import io.agora.rtc.Constants;
import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;
import io.agora.utils.Constant;

/**
 * Created by yt on 2018/8/15/015.
 */

public class RoomActivity extends Activity {
    private static final int PERMISSION_REQ_ID_RECORD_AUDIO = 22;

    private ListView mListView;
    private TextView mTextViewTitle;
    private CheckBox mCheckBoxToBroadCast;
    private CheckBox mCheckBoxSpeakOut;
    private CheckBox mCheckBoxMuteLocalAudio;
    private CheckBox mCheckBoxMuteRemoteAudio;
    private CheckBox mCheckBoxAudioMixing;
    private CheckBox mCheckBoxAudioAccents;
    private SeekBar seekBar;
    private TextView mTvMixingVolume;
    private SeekBar mSbSignal;
    private TextView mTvSignalVolume;
    private Button mBtnStartRecord;
    private Button mBtnStopRecord;
    private String mChannelName;
    private String mTitleName;

    private boolean bIsBroadCaster = false;
    private int mRoomMode;
    private long mUid;
    private boolean USE_QTT_RTC = true;
    private RtcEngine mRtcEngine;
    private List<User> mUserList = new ArrayList<>();
    private UsesAdapter mAdapter;
    private int mChangeVolumnIndex = -1;
    // uid 在 onJoinChannelSuccess 回调中进行赋值，值来自服务器生成的唯一随机数。这个随机数用 uid 记录
    private int mLocalUid;
    private Context mContext;
    private AlertDialog dialog;
    private boolean mIsLeaveChannel;

    private static final int WHAT_ON_OVER_CONN = 1;
    private static final int WHAT_ON_RECONN = 2;
    private int mReJoinCount = 0;
    private boolean isRecording=false;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case WHAT_ON_OVER_CONN: //用户报警
                    Log.i("qtt_debug", "第一个消息是：");
                    break;

                case WHAT_ON_RECONN: //重连
                    mReJoinCount++;
                    Log.i("qtt_debug", "第二个消息是：" + mReJoinCount);
//                    mRtcEngine.leaveChannel();
                    mRtcEngine.joinChannel("00628d8355cb09645348b0811ee6e0d9e5dIADErF+B1wCTY395SRW4042UhWJ8ZMAXT8ZFrWrqifh8w4Sb/6UAAAAAEACkrF/0HnBOXgEAAQAecE5e",
                            "19988002", "", (int) mUid);
                    break;
            }
        }
    };
    /**
     * 声网频道内业务回调
     */
    private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() {

        @Override
        public void onUserJoined(final int uid, int elapsed) {
            Log.d("qtt_debug", "onUserJoined " + uid + ", elapsed=" + elapsed);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // 当有用户加入时，添加到用户列表
                    mUserList.add(new User(uid, 0, false, false));
                    mAdapter.notifyDataSetChanged();
                }
            });
        }


        @Override
        public void onUserOffline(final int uid, int reason) {
            Log.d("qtt_debug", "onUserOffline " + uid + ", reason=" + reason);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // 当用户离开时，从用户列表中清除
                    int index = getUserIndex(uid);
                    if (index < 0)
                        return;
                    mUserList.remove(index);
                    mAdapter.notifyDataSetChanged();
                }
            });
        }

        @Override
        public void onUserMuteAudio(final int uid, final boolean muted) {
            Log.d("qtt_debug", "onUserMuteAudio " + uid + ", muted=" + muted);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // 收到某个uid mute 状态后刷新人员列表
                    int index = getUserIndex(uid);
                    if (index < 0)
                        return;
                    mUserList.get(index).setAudioMute(muted);
                    mAdapter.notifyDataSetChanged();
                }
            });
        }

        private void rejoin() {
            if (mHandler.hasMessages(WHAT_ON_RECONN)) {
                return;
            }
            if (mReJoinCount < 3) {
//                mRtcEngine.leaveChannel();
                mHandler.removeCallbacksAndMessages(null);
                mHandler.sendEmptyMessageDelayed(WHAT_ON_RECONN, 10000);//10秒重连一次
            } else {
                mHandler.removeCallbacksAndMessages(null);
                mHandler.sendEmptyMessage(WHAT_ON_OVER_CONN);
            }
        }

        @Override
        public void onWarning(int warn) {
            super.onWarning(warn);
            Log.d("qtt_debug", "onWarning " + warn);
            if (mIsLeaveChannel) {
                return;
            }
            if (warn == 103 || warn == 104 || warn == 105 || warn == 106 || warn == 107) {
                rejoin();
            }
        }

        @Override
        public void onError(int err) {
            super.onError(err);
            Log.d("qtt_debug", "onError " + err);
            if (mIsLeaveChannel) {
                return;
            }
            if (err == 17 || err == 102 || err == 110) {
                rejoin();
            }
        }

        @Override
        public void onJoinChannelSuccess(final String channel, final int uid, int elapsed) {
            Log.d("qtt_debug", "channel " + channel + ", uid=" + uid + ", elapsed=" + elapsed);
            if (mIsLeaveChannel) {
                return;
            }
            mUid = uid;
            mHandler.removeCallbacksAndMessages(null);
            mReJoinCount = 0;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(mContext, "加入成功", Toast.LENGTH_SHORT).show();
                    // onJoinChannelSuccess 回调中，uid 不会为0
                    // 当 joinChannel api 中填入 0 时，agora 服务器会生成一个唯一的随机数，并在 onJoinChannelSuccess 回调中返回
                    mLocalUid = uid;
                    mUserList.clear();
                    /** 进入频道，主播状态下将自己加入到 user 列表**/
                    if (bIsBroadCaster) {
                        mUserList.add(new User(uid, 0, false, true));
                    }
                    if (mAdapter != null)
                        mAdapter.notifyDataSetChanged();
                }
            });
        }

        @Override
        public void onRejoinChannelSuccess(String channel, int uid, int elapsed) {
            super.onRejoinChannelSuccess(channel, uid, elapsed);
            Log.d("qtt_debug", "onRejoinChannelSuccess ");
            if (mIsLeaveChannel) {
                return;
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(mContext, "重连成功", Toast.LENGTH_SHORT).show();
                }
            });
            Log.d("qtt_debug", "onRejoinChannelSuccess 1 ");
            mHandler.removeCallbacksAndMessages(null);
            Log.d("qtt_debug", "onRejoinChannelSuccess 2 ");

            mReJoinCount = 0;
        }

        @Override
        public void onLeaveChannel(IRtcEngineEventHandler.RtcStats stats) {
            Log.d("qtt_debug", "onLeaveChannel ");
        }

        @Override
        public void onConnectionStateChanged(int state, int reason) {
            Log.d("qtt_debug", "onConnectionStateChanged " + state + ", reason=" + reason);
        }

        /**
         * @deprecated
         */
        @Override
        public void onConnectionInterrupted() {
            super.onConnectionInterrupted();
            Log.d("qtt_debug", "onConnectionInterrupted ");
            mHandler.removeCallbacksAndMessages(null);
            mHandler.sendEmptyMessageDelayed(WHAT_ON_OVER_CONN, 30000);//总共30秒的自动重连时间
        }

        @Override
        public void onClientRoleChanged(int oldrole, int newrole) {
            Log.d("qtt_debug", "onClientRoleChanged old=" + oldrole + ", newrole=" + newrole);
        }

        @Override
        public void onConnectionLost() {
            super.onConnectionLost();
            Log.d("qtt_debug", "onConnectionLost ");
        }

        @Override
        public void onAudioVolumeIndication(final IRtcEngineEventHandler.AudioVolumeInfo[] speakers, int totalVolume) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (speakers != null) {
                        for (IRtcEngineEventHandler.AudioVolumeInfo audioVolumeInfo : speakers) {
//                            Log.d("qtt_debug", "audioVolumeInfo uid="+audioVolumeInfo.uid+", vad="+audioVolumeInfo.vad+", vol="+audioVolumeInfo.volume);
                            /**
                             * 根据uid判断是他人还是自己， uid 0 默认是自己，根据 uid = 0 的取本地音量值，和joinchannelsuccess 内
                             * 本地的 LocalUid 对应
                             *
                             */
                            if (audioVolumeInfo.uid != 0) {
                                int index = getUserIndex(audioVolumeInfo.uid);
                                if (index >= 0) {
                                    mUserList.get(index).setAudioVolum(audioVolumeInfo.volume);
                                }
                            } else {
                                int index = getUserIndex(mLocalUid);
                                if (index >= 0) {
                                    mUserList.get(index).setAudioVolum(audioVolumeInfo.volume);
                                }
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                }
            });
        }

        @Override
        public void onAudioMixingFinished() {
            super.onAudioMixingFinished();
            /** 伴奏播放结束时，将button 置为未选中状态 **/
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mCheckBoxAudioMixing.setChecked(false);
                }
            });
        }
    };


    private int getUserIndex(int uid) {
        for (int i = 0; i < mUserList.size(); i++) {
            if (mUserList.get(i).getUid() == uid) {
                return i;
            }
        }
        return -1;
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mIsLeaveChannel = true;
        if (USE_QTT_RTC) {
            //先转成QttRtcEngine对象，才有delete方法
            QttRtcEngine tmp = (QttRtcEngine) mRtcEngine;
            tmp.delete();
            //todo 上传日志，然后删除日志
        } else
            RtcEngine.destroy();
    }

    // 要申请的权限
    private String[] permissions = {Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_room);
        mContext = this;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            boolean has_permissions = true;
            // 检查该权限是否已经获取
            for (String permission : permissions) {
                int i = ContextCompat.checkSelfPermission(this, permission);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 如果没有授予该权限，就去提示用户请求
                    showDialogTipUserRequestPermission();
                    has_permissions = false;
                    break;
                }
            }
            if (has_permissions) {
                initAgoraEngineAndJoinChannel();
            }
        }else {
            initAgoraEngineAndJoinChannel();
        }


//        /***
//         * 动态申请权限
//         */
//        if (checkSelfPermission(Manifest.permission.RECORD_AUDIO, PERMISSION_REQ_ID_RECORD_AUDIO)) {
//            initAgoraEngineAndJoinChannel();
//        }
    }

    // 提示用户该请求权限的弹出框
    private void showDialogTipUserRequestPermission() {
        new AlertDialog.Builder(this)
                .setTitle("麦克风权限不可用")
                .setMessage("由于该应用需要麦克风，采集音频数据；\n否则，您将无法正常使用该应用")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions(RoomActivity.this, permissions, PERMISSION_REQ_ID_RECORD_AUDIO);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }

    // 提示用户去应用设置界面手动开启权限
    private void showDialogTipUserGoToAppSettting() {
        dialog = new AlertDialog.Builder(this)
                .setTitle("麦克风权限不可用")
                .setMessage("请在-应用设置-权限-中，允许该应用使用麦克风权限来获取音频数据")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, 123);
    }


    public boolean checkSelfPermission(String permission, int requestCode) {

        if (ContextCompat.checkSelfPermission(this,
                permission)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{permission},
                    requestCode);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[], @NonNull int[] grantResults) {

        switch (requestCode) {
            case PERMISSION_REQ_ID_RECORD_AUDIO: {
//                if (grantResults.length > 0
//                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    initAgoraEngineAndJoinChannel();
//                } else {
//                    showLongToast("No permission for " + Manifest.permission.RECORD_AUDIO);
//                    finish();
//                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                        // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                        boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                        if (!b) {
                            // 用户还是想用我的 APP 的
                            // 提示用户去应用设置界面手动开启权限
                            showDialogTipUserGoToAppSettting();
                        } else
                            finish();
                    } else {
                        initAgoraEngineAndJoinChannel();
                        Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            }

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 123) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 检查该权限是否已经获取
                int i = ContextCompat.checkSelfPermission(this, permissions[0]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 提示用户应该去应用设置界面手动开启权限
                    showDialogTipUserGoToAppSettting();
                } else {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    public final void showLongToast(final String msg) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        });
    }

    private void initAgoraEngineAndJoinChannel() {

        setupData();

        try {
            if (USE_QTT_RTC) {
                // 初始化QttSDK对象
                mRtcEngine = new QttRtcEngine(getBaseContext(), Constant.getAppId(USE_QTT_RTC), mRtcEventHandler);
            } else {
                // 初始化声网SDK对象
                mRtcEngine = RtcEngine.create(getBaseContext(), Constant.getAppId(USE_QTT_RTC), mRtcEventHandler);
            }

            mRtcEngine.setLogFile("/sdcard/chatRoom.log"); //qtt未实现

        } catch (Exception e) {

            throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
        }


        setupUI();

        /** 根据房间类型设置 audioProfile **/
        switch (mRoomMode) {
            case Constant.ChatRoomGamingStandard:
                /** 开黑聊天室 */
                mRtcEngine.setAudioProfile(Constants.AUDIO_PROFILE_SPEECH_STANDARD, Constants.AUDIO_SCENARIO_CHATROOM_GAMING);
                break;
            case Constant.ChatRoomEntertainmentStandard:
                /** 娱乐聊天室 */
                mRtcEngine.setAudioProfile(Constants.AUDIO_PROFILE_MUSIC_STANDARD, Constants.AUDIO_SCENARIO_GAME_STREAMING);
                break;
            case Constant.ChatRoomEntertainmentHighQuality:
                /** K 歌房 */
                mRtcEngine.setAudioProfile(Constants.AUDIO_PROFILE_MUSIC_HIGH_QUALITY, Constants.AUDIO_SCENARIO_CHATROOM_ENTERTAINMENT);
                break;
            case Constant.ChatRoomGamingHighQuality:
                /** FM 超高音质**/
                mRtcEngine.setAudioProfile(Constants.AUDIO_PROFILE_MUSIC_HIGH_QUALITY_STEREO, Constants.AUDIO_SCENARIO_CHATROOM_ENTERTAINMENT);
                break;
        }
        mRtcEngine.setChannelProfile(Constants.CHANNEL_PROFILE_LIVE_BROADCASTING);
        // 启动音量监听
        mRtcEngine.enableAudioVolumeIndication(1000, 3, true);
//        mRtcEngine.setDefaultAudioRoutetoSpeakerphone(true);
//        mRtcEngine.muteLocalAudioStream(true);
        // 当 joinChannel api 中填入 0 时，agora 服务器会生成一个唯一的随机数，并在 onJoinChannelSuccess 回调中返回
        mIsLeaveChannel = false;
        mRtcEngine.joinChannel(Constant.getToken(), Constant.getRoomId(),"", 0);

    }

    /**
     * 获取从上一个界面传过来的频道信息，角色信息
     */
    private void setupData() {
        Intent intent = getIntent();
        if (intent != null) {
            USE_QTT_RTC = intent.getBooleanExtra("use_qtt", true);
            mRoomMode = intent.getIntExtra(Constant.ACTION_KEY_ROOM_MODE, Constant.ChatRoomGamingStandard);
            bIsBroadCaster = intent.getIntExtra(Constant.ACTION_KEY_CROLE, Constants.CLIENT_ROLE_BROADCASTER) == Constants.CLIENT_ROLE_BROADCASTER;
            mChannelName = intent.getStringExtra(Constant.ACTION_KEY_ROOM_NAME);
            mTitleName = intent.getStringExtra(Constant.ACTION_KEY_TITLE_NAME);
        }
    }

    private void setupUI() {
        mTextViewTitle = (TextView) findViewById(R.id.room_name);
        mListView = (ListView) findViewById(R.id.room_listview);
        mTextViewTitle.setText(mTitleName);
        mAdapter = new UsesAdapter(this, mUserList);
        mListView.setAdapter(mAdapter);

        mBtnStartRecord = findViewById(R.id.btn_start_record);
        mBtnStopRecord = findViewById(R.id.btn_stop_record);
        mCheckBoxToBroadCast = (CheckBox) findViewById(R.id.room_to_broadcast);
        mCheckBoxSpeakOut = (CheckBox) findViewById(R.id.room_speak_out);
        mCheckBoxMuteLocalAudio = (CheckBox) findViewById(R.id.room_mute_self);
        mCheckBoxMuteRemoteAudio = (CheckBox) findViewById(R.id.room_mute_other);
        mCheckBoxAudioMixing = (CheckBox) findViewById(R.id.room_audio_mixing);
        mCheckBoxAudioAccents = (CheckBox) findViewById(R.id.room_audio_accents);
        seekBar = findViewById(R.id.seekBar);
        mSbSignal = findViewById(R.id.sb_signal);
        mTvMixingVolume = findViewById(R.id.tv_mixingVolume);
        mTvSignalVolume = findViewById(R.id.tv_signalVolume);

        seekBar.setProgress(50);
        mSbSignal.setProgress(100);
        mTvMixingVolume.setText("伴奏音量：50");
        mTvSignalVolume.setText("人声音量：100");

        mCheckBoxToBroadCast.setOnCheckedChangeListener(onCheckedChangeListener);
        mCheckBoxSpeakOut.setOnCheckedChangeListener(onCheckedChangeListener);
        mCheckBoxMuteLocalAudio.setOnCheckedChangeListener(onCheckedChangeListener);
        mCheckBoxMuteRemoteAudio.setOnCheckedChangeListener(onCheckedChangeListener);
        mCheckBoxAudioMixing.setOnCheckedChangeListener(onCheckedChangeListener);
        mCheckBoxAudioAccents.setOnCheckedChangeListener(onCheckedChangeListener);
        seekBar.setOnSeekBarChangeListener(new MyOnSeekBarChangeListener(){
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                super.onProgressChanged(seekBar, progress, fromUser);
                Log.d("progress", "onProgressChanged: " + progress);
                seekBar.setProgress(progress);
                mRtcEngine.adjustAudioMixingVolume(progress);
                mTvMixingVolume.setText("伴奏音量："+progress);
            }
        });

        mSbSignal.setOnSeekBarChangeListener(new MyOnSeekBarChangeListener(){
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                super.onProgressChanged(seekBar, progress, fromUser);
                seekBar.setProgress(progress);
                mRtcEngine.adjustRecordingSignalVolume(progress);
                mTvSignalVolume.setText("人声音量："+progress);
            }
        });
        /**
         * 刚进入时根据是观众还是主播状态做一次UI控制，伴奏，变音，静音自己按钮不可点击
         * */
        if (bIsBroadCaster) {
            mCheckBoxToBroadCast.setChecked(true);
            showBroadCast();
        } else {
            mCheckBoxToBroadCast.setChecked(false);
            showAudience();
        }
    }

    /**
     * 上下麦，声音外放，本地听筒 mute 按钮和 microphone mute 按钮状态切换
     **/
    private CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            switch (buttonView.getId()) {
                case R.id.room_to_broadcast:
                    bIsBroadCaster = isChecked;
                    if (isChecked) {
                        showBroadCast();
                    } else {
                        showAudience();
                    }
                    break;
                case R.id.room_speak_out:
                    // 切换听筒还是外放
                    mRtcEngine.setEnableSpeakerphone(isChecked);
                    break;
                case R.id.room_mute_other:
                    mRtcEngine.muteAllRemoteAudioStreams(isChecked);
                    break;
                case R.id.room_mute_self:
                    mRtcEngine.muteLocalAudioStream(isChecked);
                    break;
                case R.id.room_audio_mixing:
                    // 播放伴奏音乐
                    if (isChecked) {
                        mRtcEngine.startAudioMixing("/assets/tonight1.mp3", false, false, -1);
                        // 调整伴奏音量，防止伴奏声音过大影响人声
                        mRtcEngine.adjustAudioMixingVolume(50);
                    } else {
                        mRtcEngine.stopAudioMixing();
                    }

                    break;
                case R.id.room_audio_accents:
                    showPopuWindowMenu(buttonView);
                    break;
            }
        }
    };

    /**
     * 通过popuwindow 显示变色的选项
     *
     * @param parentView
     */
    private void showPopuWindowMenu(final View parentView) {
        View conventView = LayoutInflater.from(this).inflate(R.layout.activity_popuwindow, null, false);
        final PopupWindow popupWindow = new PopupWindow(conventView, 300, RelativeLayout.LayoutParams.WRAP_CONTENT, true);

        ListView listview = (ListView) conventView.findViewById(R.id.pop_listview);
        final PopuwindowAdapter popAdapter = new PopuwindowAdapter(this);
        popAdapter.setSelectIndex(mChangeVolumnIndex);
        listview.setAdapter(popAdapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                /**
                 * 选择事件，如果是当前选项，则取消选中，设默认值。不是则修改选中条目背景色
                 * **/

                if (position == mChangeVolumnIndex) {
                    mChangeVolumnIndex = -1;
                    mCheckBoxAudioAccents.setBackgroundColor(getResources().getColor(R.color.gray));
                } else {
                    mChangeVolumnIndex = position;
                    mCheckBoxAudioAccents.setBackgroundColor(getResources().getColor(R.color.agora_blue));
                }

//                SoundEffectUtil.changeEffect(mRtcEngine, mChangeVolumnIndex + 1);
                popAdapter.setSelectIndex(position);
                popAdapter.notifyDataSetChanged();
                ((CheckBox) parentView).setText(Constant.SOUNDARRAY[position]);
                popupWindow.dismiss();
            }
        });

        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {

            int[] location = new int[2];
            parentView.getLocationOnScreen(location);

            DisplayMetrics displayMetrics = new DisplayMetrics();
            WindowManager windowManager = getWindowManager();
            windowManager.getDefaultDisplay().getMetrics(displayMetrics);
            popupWindow.showAtLocation(parentView, Gravity.LEFT | Gravity.BOTTOM, location[0], (int) (displayMetrics.heightPixels - location[1] + 40 * displayMetrics.density));

        } else {
            popupWindow.showAsDropDown(parentView, 0, 8);
        }


    }

    /**
     * 上麦界面
     */
    private void showBroadCast() {

        // 设置为主播
        mRtcEngine.setClientRole(Constants.CLIENT_ROLE_BROADCASTER);
        // role 改变后需要将自己添加到用户列表
        if (mLocalUid != 0) {
            mUserList.add(new User(mLocalUid, 0, false, true));
            mAdapter.notifyDataSetChanged();
        }
        // 上麦状态下，部分功能按钮可点击
        mCheckBoxAudioAccents.setEnabled(true);
        mCheckBoxAudioMixing.setEnabled(true);
        mCheckBoxMuteLocalAudio.setEnabled(true);
        mCheckBoxSpeakOut.setChecked(true);

    }

    /**
     * 下麦界面
     */
    private void showAudience() {
        //设为观众
        mRtcEngine.setClientRole(Constants.CLIENT_ROLE_AUDIENCE);
        if (mCheckBoxAudioMixing.isChecked()) {
            mCheckBoxAudioMixing.setChecked(false);
        }
        // role 为观众后需要将自己从用户列表移除
        int index = getUserIndex(mLocalUid);
        if (index >= 0) {
            mUserList.remove(index);
        }
        mAdapter.notifyDataSetChanged();

        // 下麦状态下，部分功能按钮不可点击
        mCheckBoxAudioAccents.setEnabled(false);
        mCheckBoxAudioMixing.setEnabled(false);
        mCheckBoxMuteLocalAudio.setEnabled(false);
        // 下麦状态下，伴奏按钮状态还原
        mCheckBoxAudioMixing.setChecked(false);
        mCheckBoxMuteLocalAudio.setChecked(false);

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        leaveChannel();
    }

    /**
     * 退出按钮点击事件
     *
     * @param view
     */
    public void finishRoom(View view) {
        leaveChannel();
    }

    /**
     * 离开频道
     **/
    private void leaveChannel() {
        if (mRtcEngine != null) {
            mIsLeaveChannel = true;
            mRtcEngine.leaveChannel();
        }
        finish();
    }

    public void stopRecord(View view) {
        if(isRecording){
            mRtcEngine.stopAudioRecording();
            isRecording=false;
            mBtnStartRecord.setBackgroundColor(getResources().getColor(R.color.gray));
            mBtnStopRecord.setBackgroundColor(getResources().getColor(R.color.gray));
            mBtnStartRecord.setText("录音");
        }
    }

    public void record(View view) {
        if(isRecording){
            Toast.makeText(mContext, "录音中", Toast.LENGTH_SHORT).show();
            return;
        }
        if (USE_QTT_RTC) {
            mRtcEngine.startAudioRecording("/mnt/sdcard/qtt_record.wav", 2);
        } else {
            mRtcEngine.startAudioRecording("/mnt/sdcard/record.wav", 2);
        }
        isRecording=true;
        mBtnStartRecord.setBackgroundColor(getResources().getColor(R.color.agora_blue));
        mBtnStopRecord.setBackgroundColor(getResources().getColor(R.color.red));
        mBtnStartRecord.setText("录音中");
    }
}
